package com.cloudcc.boot.utils.util;

import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import jakarta.servlet.http.HttpServletRequest;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.text.SimpleDateFormat;
import java.util.*;

public class HttpClientUtil {

    public HttpClientUtil() {
    }

    public static String doGet(String url, Map<String, String> param) throws IOException, URISyntaxException {

        // 创建Httpclient对象
        CloseableHttpClient httpclient = HttpClients.createDefault();

        String resultString = "";
        CloseableHttpResponse response = null;
        try {
            // 创建uri
            URIBuilder builder = new URIBuilder(url);
            if (param != null) {
                for (String key : param.keySet()) {
                    builder.addParameter(key, param.get(key));
                }
            }
            URI uri = builder.build();
            // 创建http GET请求
            HttpGet httpGet = new HttpGet(uri);
            RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(5000)
                    .setSocketTimeout(5000).setConnectTimeout(5000).build();
            httpGet.setConfig(requestConfig);
            // 执行请求
            response = httpclient.execute(httpGet);
            // 判断返回状态是否为200
            if (response.getStatusLine().getStatusCode() == 200) {
                resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
            }
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return resultString;
    }

    public static String doGet(String url) throws IOException, URISyntaxException {
        return doGet(url, null);
    }

    public static String doPost(String url, Map<String, String> param) throws IOException {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);
            RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(5000)
                    .setSocketTimeout(5000).setConnectTimeout(5000).build();
            httpPost.setConfig(requestConfig);
            // 创建参数列表
            if (param != null) {
                List<NameValuePair> paramList = new ArrayList<>();
                for (String key : param.keySet()) {
                    paramList.add(new BasicNameValuePair(key, param.get(key)));
                }
                // 模拟表单
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList);
                httpPost.setEntity(entity);
            }
            httpPost.addHeader("ower","ower");
            // 执行http请求
            response = httpClient.execute(httpPost);
            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return resultString;
    }

    public static String doPost(String url) throws IOException {
        return doPost(url, null);
    }

    public static String doPostJson(String url, String json) throws IOException {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);
            RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(5000)
                    .setSocketTimeout(5000).setConnectTimeout(5000).build();
            httpPost.setConfig(requestConfig);
            // 创建请求内容
            StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
            httpPost.setEntity(entity);
            Date now = new Date();
            SimpleDateFormat sdft = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss:SSS");
            String datestr = sdft.format(now);
            //同步产品
            String serviceName = "cloudcc";
            String token = MD5.MD5Encode(serviceName + datestr + ConstantUtil.VERIFY_CODE);
            httpPost.addHeader("serviceName",serviceName);
            httpPost.addHeader("timestamp",datestr);
            httpPost.addHeader("verifyCode",token);
            // 执行http请求
            response = httpClient.execute(httpPost);
            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return resultString;
    }
/*    1、发送正常格式数据
    客户端：*/
    public static void httpClientTest() throws IOException {
        Map<String, String> param = new HashMap<String, String>();
        param.put("username", "xiaoming");
        String url="http://127.0.0.1:8080/TestDemo/httpClientResp";
        String str = HttpClientUtil.doPost(url, param);
        System.out.println(str);
    }
//    服务端：
    @RequestMapping(value = "/httpClientResp")
    @ResponseBody
    public String httpClientResp(HttpServletRequest request){
        String username = request.getParameter("username");
        return username;
}
/*2、发送json数据
    客户端：*/
public static void httpClientJsonTest() throws IOException {
    Map<String, String> param = new HashMap<String, String>();
    param.put("username", "xiaoming");
    String postParam = param.toString();
    String url = "http://127.0.0.1:8080/TestDemo/httpClientJsonResp";
    String str = HttpClientUtil.doPostJson(url, postParam);
    System.out.println(str);
}
//    服务端：
@RequestMapping(value = "/httpClientJsonResp")
@ResponseBody
public String httpClientJsonResp(HttpServletRequest request) {
StringBuffer str = new StringBuffer();
    try {
        BufferedInputStream in = new BufferedInputStream(request.getInputStream());
        int i;
        char c;
        while ((i = in.read()) != -1) {
            c = (char) i;
            str.append(c);
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    String string = str.toString();
    return string;
}
    public static void main(String[] args) throws IOException, URISyntaxException {
//        Map<String, String> param = new HashMap<String, String>();
//        param.put("username", "xiaoming");
        String url="http://timor.tech/api/holiday/year/2021/";
        String str = HttpClientUtil.doGet(url);
        System.out.println(str);

    }
}